<?php

/**
 * Description of Http
 *
 * @author Alisson Chiquitto<chiquitto@chiquitto.com.br>
 */
class ZFKiller_Auth_Adapter_Http extends Zend_Auth_Adapter_Http {

    public function __construct(array $config = array()) {
        if (!isset($config['accept_schemes'])) {
            $config['accept_schemes'] = 'basic';
        }
        if (!isset($config['realm'])) {
            $config['realm'] = 'api';
        }

        parent::__construct($config);
    }

    protected function _basicAuth($header) {
        if ($this->_basicResolver instanceof Zend_Auth_Adapter_Http_Resolver_File) {
            return parent::_basicAuth($header);
        }
        elseif ($this->_basicResolver instanceof ZFKiller_Auth_Adapter_Http_Resolver_Db) {
            return $this->_basicDbAuth($header);
        }
        
        return $this->_challengeClient();
    }

    private function _basicDbAuth($header) {
        if (empty($header)) {
            /**
             * @see Zend_Auth_Adapter_Exception
             */
            require_once 'Zend/Auth/Adapter/Exception.php';
            throw new Zend_Auth_Adapter_Exception('The value of the client Authorization header is required');
        }

        // Decode the Authorization header
        $auth = substr($header, strlen('Basic '));
        $auth = base64_decode($auth);
        if (!$auth) {
            /**
             * @see Zend_Auth_Adapter_Exception
             */
            require_once 'Zend/Auth/Adapter/Exception.php';
            throw new Zend_Auth_Adapter_Exception('Unable to base64_decode Authorization header value');
        }

        // See ZF-1253. Validate the credentials the same way the digest
        // implementation does. If invalid credentials are detected,
        // re-challenge the client.
        if (!ctype_print($auth)) {
            return $this->_challengeClient();
        }
        // Fix for ZF-1515: Now re-challenges on empty username or password
        $creds = array_filter(explode(':', $auth));
        if (count($creds) != 2) {
            return $this->_challengeClient();
        }

        $identity = $this->_basicResolver->resolve($creds[0], $creds[1]);
        if (NULL === $identity) {
            return $this->_challengeClient();
        }
        else {
            return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, (object) $identity->toArray());
        }
    }

}